using System.Collections.ObjectModel;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using Kiwi.Container.DependencyInjection;

namespace Kiwi.Container.Wcf
{
    public class DependencyInjectionServiceBehavior : IServiceBehavior
    {
        private readonly IEnumerateDependentProperties _dependentProperties;

        public DependencyInjectionServiceBehavior(IEnumerateDependentProperties dependentProperties)
        {
            _dependentProperties = dependentProperties;
        }

        #region IServiceBehavior Members

        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase,
                                         Collection<ServiceEndpoint> endpoints,
                                         BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            foreach (var channelDispatcherBase in serviceHostBase.ChannelDispatchers)
            {
                var channelDispatcher = channelDispatcherBase as ChannelDispatcher;
                if (channelDispatcher != null)
                {
                    foreach (var endpointDispatcher in channelDispatcher.Endpoints)
                    {
                        endpointDispatcher.DispatchRuntime.MessageInspectors.Add(
                            new CallTrackingDispatchMessageInspector());
                        endpointDispatcher.DispatchRuntime.InstanceProvider =
                            new DependencyInjectionInstanceProvider(endpointDispatcher.DispatchRuntime.Type, _dependentProperties);
                    }
                }
            }
        }


        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
        }

        #endregion
    }
}